package org.example.springboot.config;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.example.springboot.entity.AIConversation;
import org.example.springboot.entity.AIMessage;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class DeepSeekClient {
    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
    private final String apiKey;
    private final OkHttpClient client;

    // 初始化API密钥
    public DeepSeekClient(String apiKey) {
        this.apiKey = apiKey;
        // 配置OkHttpClient，增加超时时间
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 发送消息并获取响应（带会话历史）
     * @param conversation 会话对象（包含历史消息）
     * @param newMessage 用户新消息
     * @return 更新后的会话对象
     */
    public AIConversation sendMessage(AIConversation conversation, String newMessage) throws IOException {
        // 添加新消息到会话历史
        AIMessage userMessage = new AIMessage();
        userMessage.setRole("user");
        userMessage.setContent(newMessage);
        conversation.getAIMessages().add(userMessage);

        // 构造API请求参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");

        List<Map<String, String>> messages = new ArrayList<>();
        for (AIMessage msg : conversation.getAIMessages()) {
            Map<String, String> messageMap = new HashMap<>();
            messageMap.put("role", msg.getRole());
            messageMap.put("content", msg.getContent());
            messages.add(messageMap);
        }

        requestBody.put("messages", messages);
        requestBody.put("temperature", 0.7);

        // 添加重试机制
        int maxRetries = 3;
        int retryCount = 0;
        long retryInterval = 1000; // 初始重试间隔1秒

        while (retryCount < maxRetries) {
            try {
                Request request = new Request.Builder()
                        .url(API_URL)
                        .addHeader("Content-Type", "application/json")
                        .addHeader("Authorization", "Bearer " + apiKey)
                        .post(RequestBody.create(
                                MediaType.parse("application/json"),
                                JSON.toJSONString(requestBody)
                        ))
                        .build();

                try (Response response = client.newCall(request).execute()) {
                    if (!response.isSuccessful()) {
                        throw new IOException("API请求失败: " + response);
                    }

                    // 解析响应
                    String responseBody = response.body().string();
                    Map<String, Object> result = JSON.parseObject(responseBody);
                    List<Map<String, Object>> choices = (List<Map<String, Object>>) result.get("choices");
                    String assistantReply = (String) ((Map<String, Object>) choices.get(0).get("message")).get("content");

                    // 将助手回复添加到会话历史
                    AIMessage assistantMessage = new AIMessage();
                    assistantMessage.setRole("assistant");
                    assistantMessage.setContent(assistantReply);
                    conversation.getAIMessages().add(assistantMessage);

                    return conversation;
                }
            } catch (SocketTimeoutException e) {
                retryCount++;
                if (retryCount >= maxRetries) {
                    throw new IOException("API请求超时，已达到最大重试次数", e);
                }

                // 指数退避策略
                try {
                    Thread.sleep(retryInterval);
                    retryInterval *= 2; // 每次重试间隔加倍
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new IOException("重试过程被中断", ie);
                }
            }
        }

        throw new IOException("API请求失败，已达到最大重试次数");
    }

    /**
     * 流式发送消息并获取响应
     * @param conversation 会话对象
     * @param newMessage 用户新消息
     * @param emitter SSE发射器用于流式响应
     */
    public void streamSendMessage(AIConversation conversation, String newMessage, SseEmitter emitter) throws IOException {
        // 添加用户消息到会话历史
        AIMessage userMessage = new AIMessage();
        userMessage.setRole("user");
        userMessage.setContent(newMessage);
        conversation.getAIMessages().add(userMessage);

        // 构造API请求参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("stream", true); // 启用流式输出

        List<Map<String, String>> messages = new ArrayList<>();
        for (AIMessage msg : conversation.getAIMessages()) {
            Map<String, String> messageMap = new HashMap<>();
            messageMap.put("role", msg.getRole());
            messageMap.put("content", msg.getContent());
            messages.add(messageMap);
        }

        requestBody.put("messages", messages);
        requestBody.put("temperature", 0.7);

        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + apiKey)
                .post(RequestBody.create(
                        MediaType.parse("application/json"),
                        JSON.toJSONString(requestBody)
                ))
                .build();

        // 使用异步调用处理流式响应
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                emitter.completeWithError(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    emitter.completeWithError(new IOException("API请求失败: " + response));
                    return;
                }

                try (ResponseBody responseBody = response.body()) {
                    if (responseBody == null) {
                        emitter.completeWithError(new IOException("响应体为空"));
                        return;
                    }

                    StringBuilder assistantReply = new StringBuilder();

                    // 处理流式响应
                    BufferedReader reader = new BufferedReader(new InputStreamReader(responseBody.byteStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.startsWith("data: ") && !line.equals("data: [DONE]")) {
                            String jsonData = line.substring(6);
                            Map<String, Object> data = JSON.parseObject(jsonData);

                            List<Map<String, Object>> choices = (List<Map<String, Object>>) data.get("choices");
                            if (choices != null && !choices.isEmpty()) {
                                Map<String, Object> delta = (Map<String, Object>) choices.get(0).get("delta");
                                if (delta != null && delta.containsKey("content")) {
                                    String contentChunk = (String) delta.get("content");
                                    assistantReply.append(contentChunk);

                                    // 发送内容块到前端
                                    try {
                                        emitter.send(SseEmitter.event().data(contentChunk));
                                    } catch (IOException e) {
                                        // 客户端可能已断开连接
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    // 将完整的助手回复添加到会话历史
                    AIMessage assistantMessage = new AIMessage();
                    assistantMessage.setRole("assistant");
                    assistantMessage.setContent(assistantReply.toString());
                    conversation.getAIMessages().add(assistantMessage);

                    emitter.complete();
                } catch (Exception e) {
                    emitter.completeWithError(e);
                }
            }
        });
    }

    /**
     * 创建新会话
     */
    public AIConversation createNewConversation() {
        AIConversation conversation = new AIConversation();
        conversation.setConversationId(UUID.randomUUID().toString());

        // 初始化消息列表并添加系统提示
        List<AIMessage> messages = new ArrayList<>();
        AIMessage systemMessage = new AIMessage();
        systemMessage.setRole("system");
        systemMessage.setContent("你是一个农业知识小助理，名字叫调教铭，专门回答农业相关的问题，包括种植技术、病虫害防治、农产品加工、农业政策等方面的知识。请用专业但易懂的语言回答用户问题。");
        messages.add(systemMessage);

        conversation.setAIMessages(messages);
        conversation.setCreateTime(System.currentTimeMillis());
        return conversation;
    }
}